package com.szgd.handler;

import com.szgd.util.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginSuccessHandler implements AuthenticationSuccessHandler,InitializingBean{
    private static Logger logger = Logger.getLogger(LoginSuccessHandler.class);
    private String defaultTargetUrl;
    private boolean forwardToDestination = false;
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void afterPropertiesSet() throws Exception {
        if(StringUtil.isBlank(this.defaultTargetUrl)){
            throw new BeanInitializationException("You must configure defaultTargetUrl for Spring security xml");
        }
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        if(this.forwardToDestination){
            logger.info("登录成功，即将跳转至： "+ this.defaultTargetUrl);
            httpServletRequest.getRequestDispatcher(this.defaultTargetUrl).forward(httpServletRequest,httpServletResponse);
        }else{
            logger.info("重定向跳转至： "+ this.defaultTargetUrl);
            this.redirectStrategy.sendRedirect(httpServletRequest,httpServletResponse,this.defaultTargetUrl);
        }
    }

    public void setDefaultTargetUrl(String defaultTargetUrl) {
        this.defaultTargetUrl = defaultTargetUrl;
    }

    public void setForwardToDestination(boolean forwardToDestination) {
        this.forwardToDestination = forwardToDestination;
    }
}
